package com.cnct.generic.dubbo.config;

import com.cnct.generic.dubbo.handler.DubboInvokeCoreHandler;
import com.cnct.generic.dubbo.handler.InvokeCoreHandler;
import com.cnct.generic.dubbo.holder.DirectReferenConfig;
import com.cnct.generic.dubbo.holder.ReferenceHolder;
import com.cnct.generic.dubbo.holder.RegistryHolder;
import com.cnct.generic.dubbo.holder.RegistryReferenConfig;
import com.cnct.generic.dubbo.properties.GenericDubboProperties;
import com.cnct.generic.dubbo.strategy.RequireReferenceStrategy;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableConfigurationProperties(GenericDubboProperties.class)
public class ApplicationConfig {


    @Bean
    public ReferenceHolder referenceHolder() {
        return new ReferenceHolder();
    }


    @Bean
    public RequireReferenceStrategy directRequireReferenceStrategy() {
        return new DirectReferenConfig(referenceHolder());
    }

    @Bean
    public RequireReferenceStrategy registryRequireReferenceStrategy() {
        return new RegistryReferenConfig(referenceHolder());
    }

    @Bean
    public RegistryHolder registryHolder(GenericDubboProperties properties) {
        return new RegistryHolder(properties);
    }


    @Bean
    public InvokeCoreHandler invokeCoreHandler(ReferenceHolder referenceHolder,
                                               RegistryHolder registryHolder,
                                               GenericDubboProperties properties) {

        return new DubboInvokeCoreHandler(referenceHolder, registryHolder, properties);
    }


    @Bean
    @ConditionalOnMissingBean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setMaxPoolSize(10);
        threadPoolTaskExecutor.setQueueCapacity(0);
        threadPoolTaskExecutor.setKeepAliveSeconds(0);
        //设置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }

}
